package com.wl156.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.wl156.R;
import com.wl156.activities.find.FindResultBase;
import com.wl156.activities.find.GoodInfo;
import com.wl156.adapters.GoodAdapter;
import com.wl156.utils.Utils;

public class MyCollectGood extends FindResultBase implements
		OnItemLongClickListener {
	protected static final String TAG = null;

	GoodAdapter mAdapter;

	Spinner mCategorySpinner;
	List<String> ids;
	List<String> names;
	List<String> counts;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_my_collect_car);

		mHeaderStub.setLayoutResource(R.layout.item_good_header);
		mHeaderStub.inflate();

		mCategorySpinner = (Spinner) findViewById(R.id.store_category);
		mCategorySpinner
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						Log.d(TAG, "onItemSelected: " + position);
						new FindTask(ids.get(position)).execute();
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		getListView().setOnItemLongClickListener(this);

		new GetMyStoreGroupTask().execute();
	}

	public class GetMyStoreGroupTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(MyCollectGood.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (result instanceof SoapObject) {
					SoapObject so = (SoapObject) result;
					ids = new ArrayList<String>();
					names = new ArrayList<String>();
					counts = new ArrayList<String>();
					for (int i = 0; i < so.getPropertyCount(); i++) {
						SoapObject line = (SoapObject) so.getProperty(i);
						String id = line.getPropertyAsString(0);
						ids.add(id);
						String name = line.getPropertyAsString(1);
						names.add(name);
						String count = line.getPropertyAsString(2);
						counts.add(count);
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							MyCollectGood.this,
							R.layout.item_simple_dropdown_1line, names);
					mCategorySpinner.setAdapter(adapter);
				} else {
					Utils.showRetryNetworkDialog(MyCollectGood.this,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new GetMyStoreGroupTask().execute();
								}
							});
				}
			} catch (Exception e) {
			}
			mDialog.dismiss();
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				return mWebServiceClient.commonGetMyStoreGroups(mCertificate);
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Intent i = new Intent(MyCollectGood.this, GoodInfo.class);
		i.putExtra("id",
				Long.valueOf(mAdapter.getItem(position).getPropertyAsString(1)));
		startActivity(i);
	}

	@Override
	protected void onLastItemVisible() {
		super.onLastItemVisible();
	}

	public class FindTask extends AsyncTask<Void, Void, Object> {
		private String id;
		ProgressDialog mDialog;

		public FindTask(String id) {
			this.id = id;
		}

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(MyCollectGood.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			mDialog.dismiss();

			if (result instanceof SoapObject) {
				SoapObject so = (SoapObject) result;

				if (so.getPropertyCount() == 0) {
					setListenScroll(false);
					mFooterProgress.setVisibility(View.GONE);
					getListView().removeFooterView(mFooterView);
					mFooterText.setText("");
					return;
				} else if (so.getPropertyCount() == 1
						&& ((SoapObject) so.getProperty(0)).getPropertyCount() == 0) {
					SoapObject so1 = (SoapObject) so.getProperty(0);
					if (so1.getPropertyCount() == 0) {
						setListenScroll(false);
						mFooterProgress.setVisibility(View.GONE);
						getListView().removeFooterView(mFooterView);
						mFooterText.setText("");
						return;
					}
				}

				getListView().removeFooterView(mFooterView);

				mItems = so;
				mAdapter = new GoodAdapter(MyCollectGood.this, mItems);
				getListView().setAdapter(mAdapter);
			} else {
				Toast.makeText(MyCollectGood.this, "网络异常，请稍候重试",
						Toast.LENGTH_LONG).show();
				// new FindTask(id).execute();
			}
		}

		@Override
		protected Object doInBackground(Void... params) {
			try {
				return mWebServiceClient
						.driverStoreGroupGetMyStoredFreightMessage(
								mCertificate, id);
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			final int position, long id) {
		AlertDialog.Builder builer = new Builder(this);
		String[] items = { "移动收藏", "删除收藏" };
		builer.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					AlertDialog.Builder builer = new Builder(MyCollectGood.this);
					String[] items = new String[names.size()];
					names.toArray(items);
					builer.setItems(items,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										final int which) {
									String storeId = String.valueOf(mAdapter
											.getItemId(position));
									String groupId = ids.get(which);
									new MoveGroupItemTask(storeId, groupId)
											.execute();
								}
							});
					builer.show();
					break;
				case 1:
					new AsyncTask<Void, Void, Object>() {
						ProgressDialog mDialog;

						@Override
						protected void onPreExecute() {
							mDialog = ProgressDialog.show(MyCollectGood.this,
									"", "删除中");
						};

						@Override
						protected void onPostExecute(Object result) {
							mDialog.dismiss();
							if (result instanceof SoapPrimitive) {
								SoapPrimitive message = (SoapPrimitive) result;
								Toast.makeText(MyCollectGood.this,
										message.toString(), Toast.LENGTH_LONG)
										.show();
							} else if (result instanceof SoapObject) {
								Toast.makeText(MyCollectGood.this, "删除成功",
										Toast.LENGTH_LONG).show();

								new FindTask(ids.get(mCategorySpinner
										.getSelectedItemPosition())).execute();
								// TODO:
								// mAdapter.rem
								// ids.remove(position);
								// names.remove(position);
								// counts.remove(position);
								// mAdapter.notifyDataSetChanged();
							} else {
								Toast.makeText(MyCollectGood.this,
										"联网失败，请稍候再试", Toast.LENGTH_LONG).show();
							}
						};

						@Override
						protected Object doInBackground(Void... params) {
							try {
								String storeId = String.valueOf(mAdapter
										.getItemId(position));
								return mWebServiceClient
										.commonModifyStoreGroupRemoveItem(
												mCertificate, storeId);
							} catch (IOException e) {
								return e;
							} catch (XmlPullParserException e) {
								return e;
							}
						}
					}.execute();
					break;
				default:
					break;
				}
			}
		});
		builer.show();
		return true;
	}

	class MoveGroupItemTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;
		String storeId;
		String newGroupId;

		public MoveGroupItemTask(String storeId, String newGroupId) {
			this.storeId = storeId;
			this.newGroupId = newGroupId;
		}

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(MyCollectGood.this, "", "移动中");
		};

		@Override
		protected void onPostExecute(Object result) {
			if (result instanceof SoapObject) {
				SoapObject so = (SoapObject) result;
				Toast.makeText(MyCollectGood.this, "移动成功", Toast.LENGTH_LONG)
						.show();

				new FindTask(
						ids.get(mCategorySpinner.getSelectedItemPosition()))
						.execute();
			} else if (result instanceof SoapPrimitive) {
				Toast.makeText(MyCollectGood.this, result.toString(),
						Toast.LENGTH_LONG).show();

			} else {
				Toast.makeText(MyCollectGood.this, "网络异常，移动失败，请稍候再试",
						Toast.LENGTH_LONG).show();
			}
			mDialog.dismiss();
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				return mWebServiceClient
						.commonModifyStoreGroupMoveItemToAnotherGroup(
								mCertificate, storeId, MyCollectGood.this.ids
										.get(mCategorySpinner
												.getSelectedItemPosition()),
								newGroupId);
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	@Override
	protected String getFindName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Class getFindResultActivity() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Class getFindActivity() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected int getPhoneIndex() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	protected Class getAdapter() {
		// TODO Auto-generated method stub
		return null;
	}
}
